package se137.hrbust.hlgshopping137.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import se137.hrbust.hlgshopping137.dto.LoginRequest137;
import se137.hrbust.hlgshopping137.dto.LoginResponse137;
import se137.hrbust.hlgshopping137.entity.User137;
import se137.hrbust.hlgshopping137.service.UserService137;
import se137.hrbust.hlgshopping137.utils.Result137;

@RestController
@RequestMapping("/auth")
public class AuthController137 {
    @Autowired
    UserService137 userService137;
    @PostMapping("/login")
    public Result137<LoginResponse137> login(@RequestBody LoginRequest137 loginRequest137){
        try {
            LoginResponse137 response137 =  userService137.login(loginRequest137);
            return new Result137<LoginResponse137>().ok(response137);
        }catch (Exception e){
            Result137 result137 = new Result137();
            result137.setCode(400);
            result137.setMsg("FAILED");
            result137.setData(e.getMessage());
            return result137;
        }

    }
    @PostMapping("/logout")
    public Result137 logout(@RequestHeader("Authorization") String token) {
        if (token != null && token.startsWith("Bearer "))
            token = token.substring(7);
        try {
            boolean result = userService137.logout(token);
            if (!result)
                return new Result137().fail("登出失败");
            return new Result137().ok("登出成功");
        } catch (Exception e) {
            Result137 result137 = new Result137();
            result137.setCode(400);
            result137.setMsg("failed");
            result137.setData(e.getMessage());
            return result137;
        }
    }
      @PostMapping("/validate")
    public Result137 validateToken(@RequestHeader("Authorization") String token) {
        if (token != null && token.startsWith("Bearer "))
            token = token.substring(7);
        return userService137.validateToken(token) ? new Result137().ok("有效") : new Result137().fail("无效");
    }
    @PostMapping("/register")
    public Result137<String> register(@RequestBody User137 user){
        try{
            userService137.register(user);
            return new Result137<String>().ok("注册成功");
        }catch (Exception e){
            return new Result137<String>().fail("注册失败："+e.getMessage());
        }
    }

}



